import {currencyPrecisionCal, messages, queryCurrencyPrecision} from "share/common";
import React from 'react'
import {Form, Input, Switch, Icon, Select, Radio, Button, message, InputNumber} from 'antd'
import SelectEmployeeGroup from 'components/template/select-employee-group'
import 'styles/expense-reimbursement-control/mileage-subsidy/mileage-subsidy.scss'
import mileageSubsidyService from 'containers/expense-reimbursement-control/mileage-subsidy/mileage-subsidy.service'
import {connect} from "react-redux";

const FormItem = Form.Item;
const RadioGroup = Radio.Group;

import baseService from 'share/base.service'

class NewSubsidyRule extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      record: null,
      loading: false,
      showSelectEmployeeGroup: false,
      showSelectDept: false,
      radioValue: 'all',
      currencyList: [],
      unitOptionalUserGroup: {
        groups: []
      },
      chosenEmployeeIDs: [],
      chosenDeptIDs: [],
      mileageData: {},
      mileageNum: [],
      unitParam: {
        applicationUserGroupScope: '',
        optionalUserGroup: {
          groups: []
        },
        unitPrice: 0,
        ruleDesc: ''
      },
      tieredParam: {
        applicationUserGroupScope: '',
        optionalUserGroup: {
          groups: []
        },
        stepPrice: '',
      }
    }
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.params && nextProps.params === this.state.mileageData) return
    this.setState({chosenEmployeeIDs: []})
    this.props.form.resetFields();
    if (nextProps.params.key === 'tiered-price-model') {                //阶梯模式
      if (!nextProps.params.isNew) {                                    //编辑
        this.setState({record: nextProps.params.record, mileageData: nextProps.params}, () => {
          this.tieredEdit()
        })
      } else {                                                          //新建
        this.setState({mileageData: nextProps.params}, () => {
          this.tieredNew()
        });
      }
    } else {
      //单价模式
      if (!nextProps.params.isNew) {
        this.setState({record: nextProps.params.record, mileageData: nextProps.params}, () => {
          this.unitEdit()                                          //编辑
        })
      } else {
        this.setState({mileageData: nextProps.params}, () => {
          this.setState({radioValue: 'all'})
        })
      }
    }
  }

  componentWillMount() {
    this.getCurrencyList();
  }

  //阶梯模式编辑
  tieredEdit = () => {
    const {record, mileageData} = this.state;
    let value = [];
    let temp = {};
    let Group = []
    let stepPrice = record.stepPrice ? record.stepPrice.split('/') : []
    if (record) this.state.tieredParam.optionalUserGroup.groups = record.optionalUserGroup.groups
    record && record.optionalUserGroup.groups && record.optionalUserGroup.groups.map(item => {
      let tempValue = {
        value: item.userGroupOID
      }
      Group.push(tempValue)
    })
    this.setState({chosenEmployeeIDs: Group}, () => {
      if (Group.length > 0) {
        this.setState({radioValue: 'byGroup'})
      } else {
        this.setState({radioValue: 'all'})
      }
    })
    mileageData.data && mileageData.data.map((o, f) => {
      if (f === mileageData.data.length - 1) {
        temp = {
          key: `amount${f}`,
          label: messages('common.more.than', {number: mileageData.data[f].startUnit}),
          value: stepPrice[f]
        };
      } else {
        temp = {
          key: `amount${f}`,
          label: `${mileageData.data[f].startUnit}~${mileageData.data[f].endUnit}`,
          value: stepPrice[f]
        };
      }
      value.push(temp)
    })
    this.setState({mileageNum: value})
  }

  //阶梯模式新建
  tieredNew = () => {
    const {mileageData, chosenEmployeeIDs} = this.state;
    let value = [];
    let temp = {};
    mileageData.data && mileageData.data.map((item, index) => {
      if (index === mileageData.data.length - 1) {
        temp = {
          key: `amount${index}`,
          value: messages('common.more.than', {number: mileageData.data[index].startUnit}),
          label: messages('common.more.than', {number: mileageData.data[index].startUnit})
        };
      } else {
        temp = {
          key: `amount${index}`,
          value: `${mileageData.data[index].startUnit}~${mileageData.data[index].endUnit}`,
          label: `${mileageData.data[index].startUnit}~${mileageData.data[index].endUnit}`
        };
      }
      value.push(temp)
    })
    this.setState({mileageNum: value, radioValue: 'all'}, () => {
      this.userGroupInit()
    })
  }

  //单价模式编辑
  unitEdit = () => {
    const {mileageData, unitParam} = this.state;
    let temp = [];
    if (mileageData.record && mileageData.record.optionalUserGroup) {
      unitParam.optionalUserGroup.groups = mileageData.record.optionalUserGroup.groups;
    }
    mileageData.record && mileageData.record.optionalUserGroup && mileageData.record.optionalUserGroup.groups.map(item => {
      let tempValue = {
        value: item.userGroupOID
      }
      temp.push(tempValue)
    });
    this.setState({chosenEmployeeIDs: temp, unitParam}, () => {
      if (temp.length > 0) {
        this.setState({radioValue: 'byGroup'})
      } else {
        this.setState({radioValue: 'all'})
      }
    })
  };

  //删除对象属性
  deleteObjectAttribute(obj, values) {
    values.map(item => {
      delete obj[item]
    })
  }

  //阶梯模式新建提交&&编辑
  handleTieredSubmit = (e) => {
    e.preventDefault();
    const {mileageData, mileageNum, radioValue, chosenEmployeeIDs} = this.state;
    const {isNew} = this.props;
    if (radioValue === 'byGroup' && chosenEmployeeIDs.length < 1) {
      // 请选择人员组
      message.error(messages('setting.key788'/*请选择人员组*/));
      return
    }
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let stepPrice = [];
        values = {...this.state.tieredParam, ...values};
        values.applicationUserGroupScope = radioValue === 'all' ? 1001 : 1002
        values.stepOID = mileageData.stepOID;
        values.name = values.ruleName;
        this.deleteObjectAttribute(values, ['ruleDesc', 'ruleName', 'permission']);
        mileageNum.map((o, p) => {
          for (let key in values) {
            if (key === `amount${p}`) {
              stepPrice.push(values[key]);
              delete values[`amount${p}`]
            }
          }
        })
        values.stepPrice = stepPrice.join(',');
        this.setState({loading: true});
        if (!isNew) {
          delete values.stepOID;
          values.ruleOID = mileageData.record.ruleOID
          mileageSubsidyService.changeTieredRule(values).then(response => {
            if (response.status === 200) {
              this.setState({loading: false});
              message.success(messages('setting.key260'/*修改成功*/));
              this.props.form.resetFields();
              this.userGroupInit();
              this.props.close(true)
            }
          }).catch(e => {
            this.setState({loading: false});
            // 操作失败
            message.error(`${messages('common.operate.filed')}，${e.response.data.message}`);
          });
        } else {
          mileageSubsidyService.addTieredRuleList(values).then((response) => {
            if (response.status === 200) {
              this.setState({loading: false});
              // 保存成功
              message.success(messages('common.save.success', {name: ''}));
              this.props.form.resetFields();
              this.userGroupInit();
              this.props.close(true)
            }
          }).catch(e => {
            this.setState({loading: false});
            //保存失败
            message.error(`${messages('common.save.filed')}，${e.response.data.message}`);
          });
        }
      }
    })
  };

  //单价模式新建&编辑
  handleUnitSubmit = (e) => {
    e.preventDefault();
    const {isNew} = this.props;
    if (this.state.radioValue === 'byGroup' && this.state.chosenEmployeeIDs.length < 1) {
      // 请选择人员组
      message.error(messages('setting.key788'/*请选择人员组*/));
      return !1;
    }
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (err) {
        return !1;
      }
      if (this.state.unitParam.optionalUserGroup.groups) {
        values = {...this.state.unitParam, ...values};
        values.applicationUserGroupScope = this.state.radioValue === 'all' ? 1001 : 1002
        values.unitPrice = values.money;
        values.ruleDesc = values.ruleName;
        if (!isNew) {
          values.ruleOID = this.state.record.ruleOID
        }
        this.deleteObjectAttribute(values, ['money', 'permission', 'ruleName']);
        this.setState({loading: true});
        let method = isNew ? 'post' : 'put';
        mileageSubsidyService.addUnitRuleList(method, values).then((response) => {
          if (response.status === 200) {
            this.setState({loading: false});
            // 保存成功
            message.success(messages('common.save.success', {name: ''}));
            this.props.form.resetFields();
            this.userGroupInit();
            this.props.close(true)
          }
        }).catch(e => {
          this.setState({loading: false});
          message.error(`${messages('common.save.filed')}，${e.response.data.message}`)
        });
      }
    })
  };

  //适用人员初始化
  userGroupInit = () => {
    if (this.state.mileageData.key === 'unit-price-model') {
      this.setState({
        chosenEmployeeIDs: [],
        chosenDeptIDs: [],
        unitParam: {
          optionalUserGroup: {
            groups: []
          }
        }
      })
    } else {
      this.setState({
        chosenEmployeeIDs: [],
        chosenDeptIDs: [],
        tieredParam: {
          optionalUserGroup: {
            groups: []
          }
        }
      })
    }

  };

  handleSelectEmployeeCancel = () => {
    this.setState({showSelectEmployeeGroup: false, showSelectDept: false})
  };
  //获取账套下面多币种信息
  getCurrencyList(){
    let {company, language}=this.props;
    let params = {
      tenantId: company.tenantId,
      setOfBooksId: company.setOfBooksId,
      enable: true,
      language: language.code
    }
    baseService.getAllCurrencyByLanguage('zh_cn', undefined, true).then(res => {
      this.setState({
        currencyList: res.data
      })
    })
  }
  handleSelectEmployeeOk = (values) => {
    let IDs = [];
    values.checkedEntites.map(item => {
      let tempValue = {
        value: item.userGroupOID
      }
      IDs.push(tempValue)
    });
    if (this.state.mileageData.key === 'unit-price-model') {
      this.setState({
        unitParam: {
          optionalUserGroup: {
            groups: values.checkedEntites
          }
        },
        chosenEmployeeIDs: IDs
      });
    } else {
      this.setState({
        tieredParam: {
          optionalUserGroup: {
            groups: values.checkedEntites
          }
        },
        chosenEmployeeIDs: IDs
      });
    }
    this.handleSelectEmployeeCancel()
  };

  //选择人员组
  handleShowGroupModal = () => {
    this.refs.chooserGroupBlur.focus();
    this.setState({
      showSelectEmployeeGroup: this.state.radioValue === 'byGroup'
    })
  };

  //修改适用人员
  onRadioChange = (e) => {
    this.setState({radioValue: e.target.value})
  };

  onCancel = () => {
    this.props.close()
  };

  getRuleName = () => {
    if (this.state.mileageData.key === 'unit-price-model') {
      if (this.props.record) {
        return this.props.record.ruleDesc
      } else {
        return ''
      }
    } else {
      if (this.props.record) {
        return this.props.record.name
      } else {
        return ''
      }
    }
  }
  //获取币种精度
  getCurrencyPrecision = () => {
    let {getFieldsValue, getFieldValue} = this.props.form;
    let currencyCode = getFieldsValue().hasOwnProperty('currency') ? getFieldValue('currency') : '';
    return queryCurrencyPrecision(currencyCode);
  }
  handleChangeCurrency = (value) => {
    if (value) {
      let {getFieldsValue, getFieldValue, setFieldsValue} = this.props.form;
      let {mileageData,mileageNum}=this.state;
      if(mileageData.key === 'tiered-price-model'){
        mileageNum.length > 0 && mileageNum.map(item => {
          getFieldsValue().hasOwnProperty(item.key) && setFieldsValue({[item.key]: currencyPrecisionCal(value, getFieldValue(item.key))});
        })
      }else{
        getFieldsValue().hasOwnProperty('money') && setFieldsValue({'money': currencyPrecisionCal(value, getFieldValue('money'))});
      }
    }
  }
  render() {

    const {getFieldDecorator} = this.props.form;
    const {record, company} = this.props;
    const {currencyList, radioValue, chosenEmployeeIDs, showSelectEmployeeGroup, mileageData, mileageNum, loading} = this.state
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14, offset: 1}
    };
    const inputItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 8, offset: 1}
    }
    let currencyPrecision=this.getCurrencyPrecision();
    return (
      <div>
        <Form onSubmit={mileageData.key === 'tiered-price-model' ? this.handleTieredSubmit : this.handleUnitSubmit}>
          <FormItem {...formItemLayout} label={messages('common.enabled')/*启用*/}>
            {getFieldDecorator('enabled', {
              valuePropName: 'checked',
              initialValue: record ? record.enabled : false
            })(<Switch checkedChildren={<Icon type="check"/>} unCheckedChildren={<Icon type="cross"/>}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout}
                    label={mileageData.key === 'tiered-price-model' ? messages('setting.key768'/*规则名称*/) : messages('setting.key199'/*描述*/)}>
            {getFieldDecorator('ruleName', {
              rules: [{
                required: true,
                message: messages('common.please.enter')
              }],
              initialValue: this.getRuleName()
            })(
              <Input
                placeholder={mileageData.key === 'tiered-price-model' ? messages('setting.key789'/*请输入，最多100个字符*/) : messages('setting.key790'/*请输入，最多200个字符*/)}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key770'/*币种*/)}>
            {getFieldDecorator('currency', {
              rules: [{
                required: true,
                message: messages('setting.key791'/*请选择币种*/)
              }],
              initialValue: record ? record.currency : company.baseCurrency
            })(
              <Select onChange={this.handleChangeCurrency}>
                {
                  currencyList.length>0 && currencyList.map(item => {
                    return <Option key={item.currency}>{item.currency}{this.props.language.code === 'zh_cn' ? ` ${item.currencyName}` : ''}</Option>
                  })
                }
              </Select>
            )}
          </FormItem>
          {mileageData.key === 'unit-price-model' &&
          <FormItem {...formItemLayout} label={messages('setting.key771'/*金额/公里*/)}>
            {getFieldDecorator('money', {
              rules: [{
                required: true,
                message: messages('common.please.enter')
              }],
              initialValue: record ? record.unitPrice : ''
            })(
              <InputNumber min={0} style={{width: '100%'}}
                           precision={currencyPrecision}
                           step={currencyPrecision ? 1 / Math.pow(10, currencyPrecision) : 1}
                           placeholder={messages('setting.key792'/*请输入单价*/)}/>
            )}
          </FormItem>
          }
          <FormItem {...formItemLayout} label={messages('setting.key769'/*适用人员*/)}>
            {getFieldDecorator('permission', {
              initialValue: undefined
            })(
              <div>
                <RadioGroup onChange={this.onRadioChange} value={radioValue} style={{marginBottom: 10}}>
                  <Radio value="all">{messages('setting.key793'/*全部人员*/)}</Radio>
                  <Radio value="byGroup">{messages('setting.key794'/*按人员组添加*/)}</Radio>
                </RadioGroup>
                {radioValue === 'byGroup' && (
                  <div>
                    <Select placeholder={messages('common.please.select')}
                            onFocus={this.handleShowGroupModal}
                            dropdownStyle={{display: 'none'}}/>
                    <div className={`chooser-number ${chosenEmployeeIDs.length && 'have-num'}`}
                         onClick={this.handleShowGroupModal}>
                      {messages('setting.key1468',{arg1:chosenEmployeeIDs.length})}
                    </div>
                    <input ref="chooserGroupBlur"
                           style={{position: 'absolute', top: '-9999vh', zIndex: -1}}/>
                  </div>
                )}
              </div>
            )}
          </FormItem>

          <SelectEmployeeGroup visible={showSelectEmployeeGroup}
                               onCancel={this.handleSelectEmployeeCancel}
                               onOk={this.handleSelectEmployeeOk}
                               selectedData={chosenEmployeeIDs}
                               mode='oid'
                               entity={true}/>
          {mileageData.key === 'tiered-price-model' && (
            <div>
              <hr className="setting-slid"/>
              <FormItem {...formItemLayout} label={messages('setting.key795'/*阶梯单价/公里*/)}>
              </FormItem>
              {mileageNum.map((item, index) => <FormItem {...inputItemLayout} key={item.key} label={item.label}>
                {getFieldDecorator(item.key, {
                  rules: [{
                    required: true,
                    message: messages('setting.key796'/*请输入金额*/)
                  }],
                  initialValue: (record && record.newestFlag) ? item.value : null
                })(
                  <InputNumber style={{width: '100%'}} precision={currencyPrecision}
                               step={currencyPrecision ? 1 / Math.pow(10, currencyPrecision) : 1} min={0} size="middle"
                               placeholder={messages('setting.key792'/*请输入单价*/)}/>
                )}
              </FormItem>)}
            </div>
          )}
          <div className="slide-footer">
            <Button type="primary" htmlType="submit" loading={loading}>{messages('common.save')}</Button>
            <Button onClick={this.onCancel}>{messages('common.cancel')}</Button>
          </div>
        </Form>
      </div>
    )
  }
}

const wrappedNewSubsidyRule = Form.create()(NewSubsidyRule)
function mapStateToProps(state) {
  return{
    company: state.login.company,
    language: state.main.language
  }

}
export default connect(mapStateToProps)(wrappedNewSubsidyRule)
